package br.edu.unifas.es5.bd2.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Comentario para testar commit.
 * @author Administrador
 *
 */
public class MainSequence {

	public static void main(String[] args) {
		try {
			Class.forName("org.postgresql.Driver");

			Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/aluno", "aluno",
					"aluno");
			conn.setAutoCommit(false);
			
			PreparedStatement psSeq = conn.prepareStatement("SELECT nextval('exemplo_id_seq') ");
			ResultSet rsSeq = psSeq.executeQuery();
			rsSeq.next();
			int id = rsSeq.getInt(1);
			System.out.println("novo id da sequence: " + id);
			
			
			PreparedStatement ps = conn.prepareStatement(
					"insert into exemplo (nome) values (?) ");
			ps.setString(1, "aluno 9");
			ps.execute();
			ResultSet rsKey = ps.getGeneratedKeys();
			if (rsKey.next()) {
				System.out.println("valor 1 salvo com id: " + rsKey.getInt(1));
			}

			Statement st = conn.createStatement();
			rsKey = st.executeQuery("select last_value from exemplo_id_seq");
			if (rsKey.next()) {
				System.out.println("valor 3 salvo com id: " + rsKey.getInt(1));
			}
			conn.commit();

			ps.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}
